﻿using System;
using System.Linq;
using System.Security.Permissions;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Security;
using Microsoft.SharePoint.Utilities;
using Microsoft.SharePoint.Workflow;
using TVMCORP.TVS.UTIL.Helpers;
using TVMCORP.TVS.UTIL.Utilities;
using TVMCORP.TVS.UTIL;
using TVMCORP.TVS.UTIL.Extensions;
using TVMCORP.TVS.UTIL.Utilities.Camlex;

namespace TVMCORP.TVS.ListInstances.Discussions
{
    /// <summary>
    /// List Item Events
    /// </summary>
    public class NotificationEventReciever : SPItemEventReceiver
    {
       /// <summary>
       /// An item was added.
       /// </summary>
       public override void ItemAdded(SPItemEventProperties properties)
       {

           SPListItem template = Utility.GetEmailTemplate(Constants.EMAIL_TEMPLATES_LIST_URL, "Thông báo có thảo luận mới", properties.Web);

           var currentItem = properties.ListItem;

           if (currentItem.Folder == null)
           {
               var caml = Camlex.Query().Where(p => (string)p["Title"] == properties.ListItem["Discussion Subject"].ToString()).ToString()
                   ;

               SPQuery query = new SPQuery() { Query = caml };
               currentItem = properties.List.GetItems(query)[0];
           }
           var pricipals = currentItem.GetEffectivePrincipals(SPBasePermissions.ViewListItems);

           string toEmails = "";
           foreach (var item in pricipals)
           {
               var group = properties.Web.Groups.Cast<SPGroup>().FirstOrDefault(p=>p.Name == item.LoginName);

               if (group != null)
               {
                   
                   foreach (SPUser user in group.Users)
                   {
                       if(!string.IsNullOrEmpty(user.Email))
                       toEmails += user.Email + ";";
                   }
               }
               else
               {
                   var user = properties.Web.Users.GetByID(item.ID);
                   if(user!=null && !string.IsNullOrEmpty(user.Email)){
                       toEmails += user.Email + ";";
                   }
               }
               
           }
       

           string url = properties.Web.Site.MakeFullUrl(properties.ListItem.ParentList.RootFolder.ServerRelativeUrl);
          
           url += "/Flat.aspx?RootFolder=" + SPEncode.UrlEncode(currentItem.Folder.ServerRelativeUrl);
           toEmails = toEmails.TrimEnd(new char[] { ';' });

           SendEmailHelper.SendEmailbytemplate(currentItem, template, toEmails, "test01@mailinator.com", "{$Link}:" + url);
           base.ItemAdded(properties);
       }


    }
}
